﻿#define _CRT_SECURE_NO_WARNINGS 1
//和可被 K 整除的⼦数组（medium）:https://leetcode.cn/problems/subarray-sums-divisible-by-k/
class Solution {
public:
    int subarraysDivByK(vector<int>& nums, int k) {
        int sum = 0;
        int ret = 0;
        unordered_map<int, int> hash;
        hash[0] = 1;
        for (auto x : nums)
        {
            sum += x;
            int m = (sum % k + k) % k;
            if (hash[m])
            {
                ret += hash[m];
            }
            hash[m]++;
        }
        return ret;
    }
};

//连续数组（medium）:https://leetcode.cn/problems/contiguous-array/
//v1:
class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        for (auto& x : nums)
        {
            if (x == 0)
            {
                x = -1;
            }
        }

        int sum = 0, ret = 0;
        unordered_map<int, int> hash;
        for (int i = 0; i < nums.size(); i++)
        {
            sum += nums[i];
            if (hash[sum])
            {
                int len = i + 1 - hash[sum];                    //此时的长度
                ret = max(len, ret);                         // ret：连续最长的数组的长度
            }
            if (sum == 0)
            {
                ret = i + 1;
            }
            if (hash[sum] == 0)
            {
                hash[sum] = i + 1;
            }

        }
        return ret;
    }
};

//v2:
class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        for (auto& x : nums)
        {
            if (x == 0)
            {
                x = -1;
            }
        }

        int sum = 0, ret = 0;
        unordered_map<int, int> hash;     // <sum,下标>  通过下标相减，来得到len
        hash[0] = -1;   //下标方法独有的
        for (int i = 0; i < nums.size(); i++)
        {
            sum += nums[i];
            if (hash.count(sum))    //为真，指sum有对应下标
            {
                int len = i - hash[sum];                    //此时的长度
                ret = max(len, ret);                         // ret：连续最长的数组的长度
            }
            // if(sum==0)
            // {
            //     ret=i+1;
            // }
            else
            {
                hash[sum] = i;     //下标
            }

        }
        return ret;

    }
};